from kalapankki.payment.models import Payment
import md5
def valid_payment_response(pid,ref,token,secret_key):
    if pid and ref and token:
        #create a md5 hex string using own token key
        m = md5.new("pid=%s&ref=%s&token=%s"%(pid, ref, secret_key))
        checksum = m.hexdigest()
        #check that the strings match
        if checksum == token:
            return True
    return False

def create_payment_key(payment, seller_id, secret_key):
    #md5 digest the payment details combined with our own secret key bound to the seller id
    m = md5.new("pid=%s&sid=%s&amount=%s&token=%s"%(payment.id, seller_id, payment.amount, secret_key))
    return m.hexdigest()

def get_payment_from_request(request, user_id,secret_key):
    #get the payment id from the request
    pid = request.GET.get("pid",None)
    ref = request.GET.get("ref",None)
    token = request.GET.get("checksum",None)
    if valid_payment_response(pid,ref,token,secret_key):
        try:
            payment = Payment.objects.get(user__id = user_id, id = pid, state="W")
            return payment
        except Payment.DoesNotExist:
            pass
    return None
    